<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of fDB
 *
 * @author root
 */
class Database_sDB extends SpoonDatabase implements Database_IdbCrud
{

    public function create($table, $dataArray = array())
    {
        if ($this->checkTableExists($table))
        {
            if (array_filter($dataArray, 'is_array'))
            {

                foreach ($dataArray as $row)
                {
                    $results[] = $this->create($table, $row);
                }

                return $results;
            } else
            {
                return $this->insert($table, $this->filterTableColumnArray($table, $dataArray));
            }
        }

    }

    public function deleteBy($table, $conditionArray = array())
    {

        if ($condition = $this->cleanConditionArray($table, $conditionArray))
        {

            $query = sprintf("DELETE FROM `%s` %s", $table, $condition);

            return $this->execute($query);
        }

        return FALSE;

    }

    public function getBy($table, $conditionArray = array(), $extras = array())
    {

        $conditionArray = empty($conditionArray) ? FALSE : $conditionArray;
        
        if ($condition = $this->cleanConditionArray($table, $conditionArray))
        {
            
            $extras = (is_array($extras) && count($extras) > 0) ? implode(' ', $extras) : '';
            
            return $this->getRecords(sprintf("SELECT *  FROM %s %s %s", $table, $condition, $extras));
        }

        return FALSE;

    }
    
    public function updateBy($table, $dataArray, $conditionArray = array())
    {

        if ($condition = $this->cleanConditionArray($table, $conditionArray))
        {
            if (!$this->handler)
                $this->connect();

            $dataArray = $this->filterTableColumnArray($table, $dataArray);

            $placeHolderArray = array();

            $executeArray = array();

            foreach ($dataArray as $k => $v)
            {
                $placeHolderArray[] = $k . ' = :' . $k;

                $executeArray[':' . $k] = $v;
            }

            $updateQuery = sprintf('UPDATE `%s`
                                    SET 
                                    %s
                                    %s', $table, implode(' , ', $placeHolderArray), $condition);

            $sth = $this->handler->prepare($updateQuery);
            
            return $sth->execute($executeArray);
        }

        return FALSE;

    }
    
    public function query($query)
    {
        if (!$this->handler)
        {
            $this->connect();
        }
        
        return $this->handler->query($query);
    }
    
    private function cleanConditionArray($table, $conditionArray = array(), $returnArray = FALSE)
    {

        if ($this->checkTableExists($table))
        {
            if (!is_array($conditionArray) || count($conditionArray) == 0)
            {
                return FALSE;
            }

            foreach ($conditionArray as $cKey => $cValue)
            {
                
                $cValueArray = Util::trimArray(explode(' ', $cValue));
                
                $cValueArray[0] = preg_replace('/[^a-zA-Z0-9%<>]/', '', $cValueArray[0]);
                
                if (count($cValueArray) != 3 || !$this->filterTableColumn($table, $cValueArray[0]))
                {
                    continue;
                }
                
                $conditionArray[trim($cKey)] = sprintf("`%s` %s %s", $cValueArray[0], strtoupper($cValueArray[1]), $cValueArray[2]);
            }
            
            return $returnArray ? $conditionArray : (!empty($conditionArray) ? ' WHERE ' . implode(' AND ', $conditionArray) : '');
        }

        return FALSE;

    }

    private function checkTableExists($table)
    {
        $query = sprintf("SHOW TABLES");

        $result = $this->getRecords($query);
	
        $tablesArray = array();
		
        foreach ($result as $row)
        {
            $tablesArray[] = $row['Tables_in_'.Config::get('db.database')];
        }

        return in_array($table, $tablesArray);

    }

    private function filterTableColumnArray($table, $array)
    {
        $checkIsMultiDArray = array_filter($array, 'is_array');

        if (count($checkIsMultiDArray) > 0)
        {
            return $array;
        }

        foreach ($array as $k => $v)
        {
            if (!$this->filterTableColumn($table, $k))
            {
                unset($array[$k]);
            } else
            {

                $array[$k] = $v;
            }
        }

        return $array;

    }

    private function filterTableColumn($table, $column)
    {
        if ($this->checkTableExists($table))
        {
            $query = sprintf("SHOW COLUMNS FROM `%s`", $table);

            $result = $this->getRecords($query);

            foreach ($result as $row)
            {
                if ($row['Field'] == $column)
                {
                    return TRUE;
                }
            }
        }

        return FALSE;

    }
    
    public function enums($table, $column)
    {
        $type = $this->getRecord( "SHOW COLUMNS FROM {$table} WHERE Field = '{$column}'" );
        
        $type = $type['Type'];
        
        preg_match('/^enum\((.*)\)$/', $type, $matches);
        
        foreach( explode(',', $matches[1]) as $value )
        {
             $enum[trim( $value, "'" )] = trim( $value, "'" );
        }
        return $enum;
    }

}